<?php  // $Id: lib.php,v 1.4 2010/02/16 16:34:44 jp5987 Exp $

/**
 * Library of functions and constants for module refworks
 * This file should have two well differenced parts:
 *   - All the core Moodle functions, neeeded to allow
 *     the module to work integrated in Moodle.
 *   - All the refworks specific functions, needed
 *     to implement all the module logic. Please, note
 *     that, if the module become complex and this lib
 *     grows a lot, it's HIGHLY recommended to move all
 *     these module specific functions to a new php file,
 *     called "locallib.php" (see forum, quiz...). This will
 *     help to save some memory when Moodle is performing
 *     actions across all modules.
 */


/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will create a new instance and return the id number
 * of the new instance.
 *
 * @param object $refworks An object from the form in mod_form.php
 * @return int The id of the newly inserted refworks record
 */
function refworks_add_instance($refworks) {

    $refworks->timecreated = time();

    # You may have to add extra stuff in here #
    if($refworks->autopopfolder!=''){
        try{
            global $mform;
            //file takes precedent over text
            if($uploaded=$mform->get_file_content('attachment')){
                require_once(dirname(__FILE__) . '/../../local/references/convert/refxml.php');
                $refxml = new refxml();
                if($refxml->test_data_type($uploaded,'RefWorksXML')){
                    $refworks->autopopdata = $uploaded;
                }else{
                    $refworks->autopopfolder ='';
                    $refworks->autopopdata = get_string('refworks_autopopdataerror','refworks');
                }
            }else{
                if($refworks->autopopdata!=''){
                    require_once(dirname(__FILE__) . '/../../local/references/convert/refxml.php');
                    $refxml = new refxml();
                    if(!$refxml->test_data_type(stripslashes($refworks->autopopdata),'RefWorksXML')){
                         $refworks->autopopdata = get_string('refworks_autopopdataerror','refworks');
                        $refworks->autopopfolder = '';
                    }
                }else{
                    $refworks->autopopfolder ='';
                }
            }
        }catch(Exception $e){
            print(get_string('refworks_autopopdataerror','refworks'));
            $refworks->autopopdata = get_string('refworks_autopopdataerror','refworks');
            $refworks->autopopfolder = '';
        }
    }

    return insert_record('refworks', $refworks);
}


/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will update an existing instance with new data.
 *
 * @param object $refworks An object from the form in mod_form.php
 * @return boolean Success/Fail
 */
function refworks_update_instance($refworks) {

    $refworks->timemodified = time();
    $refworks->id = $refworks->instance;

    # You may have to add extra stuff in here #
    
    //Special code for auto populate fields
    //If the folder field is set look for data file upload, else make sure it's all empty (so can be cleared)
    if($refworks->autopopfolder!=''){
        try{
            global $mform;
            //file always takes precedent over text
            if($uploaded=$mform->get_file_content('attachment')){
                require_once(dirname(__FILE__) . '/../../local/references/convert/refxml.php');
                $refxml = new refxml();
                if($refxml->test_data_type($uploaded,'RefWorksXML')){
                    $refworks->autopopdata = $uploaded;
                }else{
                    $refworks->autopopfolder='';
                    $refworks->autopopdata = get_string('refworks_autopopdataerror','refworks');
                }
            }else{
                //if no data uploaded, has already or manual entry? If not delete val so user knows there is no data
               if($refworks->autopopdata!=''){
                    require_once(dirname(__FILE__) . '/../../local/references/convert/refxml.php');
                    $refxml = new refxml();
                    if(!$refxml->test_data_type(stripslashes($refworks->autopopdata),'RefWorksXML')){
                        $refworks->autopopdata = get_string('refworks_autopopdataerror','refworks');
                        $refworks->autopopfolder = '';
                    }
                }else{
                    $refworks->autopopfolder ='';
                }
            }
        }catch(Exception $e){
            print('<div>'.get_string('refworks_autopopdataerror','refworks').'</div>');
            $refworks->autopopdata = get_string('refworks_autopopdataerror','refworks');
            $refworks->autopopfolder = '';
        }
    }else{
        $refworks->autopopdata = '';
    }
    

    return update_record('refworks', $refworks);
}


/**
 * Given an ID of an instance of this module,
 * this function will permanently delete the instance
 * and any data that depends on it.
 *
 * @param int $id Id of the module instance
 * @return boolean Success/Failure
 */
function refworks_delete_instance($id) {

    if (! $refworks = get_record('refworks', 'id', $id)) {
        return false;
    }

    $result = true;

    # Delete any dependent records here #

    if (! delete_records('refworks', 'id', $refworks->id)) {
        $result = false;
    }

    return $result;
}


/**
 * Return a small object with summary information about what a
 * user has done with a given particular instance of this module
 * Used for user activity reports.
 * $return->time = the time they did it
 * $return->info = a short text description
 *
 * @return null
 * @todo Finish documenting this function
 */
function refworks_user_outline($course, $user, $mod, $refworks) {
    $return = new stdClass();
    return $return;
}


/**
 * Print a detailed representation of what a user has done with
 * a given particular instance of this module, for user activity reports.
 *
 * @return boolean
 * @todo Finish documenting this function
 */
function refworks_user_complete($course, $user, $mod, $refworks) {
    return true;
}


/**
 * Given a course and a time, this module should find recent activity
 * that has occurred in refworks activities and print it out.
 * Return true if there was output, or false is there was none.
 *
 * @return boolean
 * @todo Finish documenting this function
 */
function refworks_print_recent_activity($course, $isteacher, $timestart) {
    return false;  //  True if anything was printed, otherwise false
}


/**
 * Function to be run periodically according to the moodle cron
 * This function searches for things that need to be done, such
 * as sending out mail, toggling flags etc ...
 *
 * @return boolean
 * @todo Finish documenting this function
 **/
function refworks_cron () {
    //this function deletes all accounts that have been continuously dormanted for more than 30 days (approx)
    try {
        $marker = time() - (30 * 86400);
        $todeleters = get_recordset_select("refworks_collab_accs","datedeleted < $marker ","","id,name,login,password");
        if(($todeleters!=false) && $todeleters->RecordCount()>0){
            include_once(dirname(__FILE__).'/../../local/references/rwapi/rwapi.php');
            //set rwapi proxy details
            GLOBAL $CFG;
            if(isset($CFG->proxyhost)){
                //setup  class with proxy that moodle is using
                if($CFG->proxyhost!=''){
                    rwapi::$proxy=$CFG->proxyhost;
                    if($CFG->proxyport!=''){
                        rwapi::$proxyport=$CFG->proxyport;
                    }
                }
            }
            if(rwapi::check_session('','VLE_account','VLEaccPa$$word')){
                include_once(dirname(__FILE__).'/collab/refworks_collab_lib.php');         
                while($rec = rs_fetch_next_record($todeleters)){     	    
            	    $account_id = $rec->id;
            	    $name = $rec->name;     
            	    $loginname = $rec->login;
                    $password = $rec->password;
                    //now delete the refworks account using the refworks api
                    $result = rwapi::delete_account($loginname, $password);
                    if($result){
                        //now delete the account details from the database
                        $dbdelete = refworks_collab_lib::delete_account($account_id);
                        mtrace('Shared Account No '.$account_id.' (\''.$name.'\') "dormant" for over 30 days (approx) has been permanently deleted.');
                    }	        	        
                }
                rs_close($todeleters); /// Close the recordset if not used anymore. Saves memory (optional but recommended).        
                rwapi::destroy_session();
            }else{
                mtrace('There has been an error with rwapi::check_session');
                return false;    
            }
        } 
    } catch(Exception $e) {
        mtrace('Unexpected exception in refworks cron: '.
            $e->getMessage().' -- '.$e->getFile().':'.$e->getLine()."\n");
    }
    return true;
}


/**
 * Must return an array of user records (all data) who are participants
 * for a given instance of refworks. Must include every user involved
 * in the instance, independient of his role (student, teacher, admin...)
 * See other modules as example.
 *
 * @param int $refworksid ID of an instance of this module
 * @return mixed boolean/array of students
 */
function refworks_get_participants($refworksid) {
    return false;
}


/**
 * This function returns if a scale is being used by one refworks
 * if it has support for grading and scales. Commented code should be
 * modified if necessary. See forum, glossary or journal modules
 * as reference.
 *
 * @param int $refworksid ID of an instance of this module
 * @return mixed
 * @todo Finish documenting this function
 */
function refworks_scale_used($refworksid, $scaleid) {
    $return = false;

    //$rec = get_record("refworks","id","$refworksid","scale","-$scaleid");
    //
    //if (!empty($rec) && !empty($scaleid)) {
    //    $return = true;
    //}

    return $return;
}


/**
 * Checks if scale is being used by any instance of refworks.
 * This function was added in 1.9
 *
 * This is used to find out if scale used anywhere
 * @param $scaleid int
 * @return boolean True if the scale is used by any refworks
 */
function refworks_scale_used_anywhere($scaleid) {
    if ($scaleid and record_exists('refworks', 'grade', -$scaleid)) {
        return true;
    } else {
        return false;
    }
}


/**
 * Execute post-install custom actions for the module
 * This function was added in 1.9
 *
 * @return boolean true if success, false on error
 */
function refworks_install() {
    return true;
}


/**
 * Execute post-uninstall custom actions for the module
 * This function was added in 1.9
 *
 * @return boolean true if success, false on error
 */
function refworks_uninstall() {
    return true;
}


//////////////////////////////////////////////////////////////////////////////////////
/// Any other refworks functions go here.  Each of them must have a name that
/// starts with refworks_
/// Remember (see note in first lines) that, if this section grows, it's HIGHLY
/// recommended to move all funcions below to a new "localib.php" file.


?>
